package com.aitao.util;

import com.alibaba.druid.DruidRuntimeException;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author : tao.ai
 * @Create : 2021/09/22 13:13
 * @Description : druid连接池工具类
 */
public final class Druid {
    // 默认加载的配置文件
    private static final String DEFAULT_CONFIGFILE = "druid.properties";
    // 数据源
    private DataSource dataSource;

    public Druid() {
        this(DEFAULT_CONFIGFILE);
    }

    public Druid(String filename) {
        loadFile(filename);
    }

    public Druid(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 加载配置文件
     *
     * @param filename 配置文件名
     */
    private void loadFile(String filename) {
        try {
            Properties properties = new Properties();
            properties.load(Druid.class.getClassLoader().getResourceAsStream(filename));
            InitializeDataSource(properties);
        } catch (IOException e) {
            throw new IllegalArgumentException("加载druid连接池配置文件失败");
        }
    }

    /**
     * 初始化数据源
     */
    private void InitializeDataSource(Properties properties) {
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new DruidRuntimeException("数据源初始化失败", e);
        }
    }

    /**
     * 获取数据源
     *
     * @return {@link javax.sql.DataSource}
     */
    public DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 获取连接
     */
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 释放连接
     */
    public void close(Statement st, Connection conn) {
        close(null, st, conn);
    }

    /**
     * 释放连接
     */
    public void close(ResultSet rs, Statement st, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new DruidRuntimeException("资源未释放", e);
        }
    }
}
